import React,{Component} from 'react';
import Head from './common/Head';
import {Button, Row, Col, Table, Upload, Icon, Input, message, Spin, Popconfirm, Tag,Modal} from 'antd';
import axios from 'axios';
import mp3 from '../assets/cg.mp3';
import Qs from 'qs'

import '../assets/css/home.css';

const confirm = Modal.confirm;

class Out extends Component{

    constructor(props){
        super(props);
        
        this.state = {
            urlpath:this.props.match.path,
            barCodeShow:"hidden",//控制条形码输入框显示不显示
            barCode:"",
            serialNumber:"",//流水号
            disabled:"",//控制确认出库按钮
            loadingflag:false,
            outLoadingflag:false,

            data : [],
            outData : [],
            columns : [{
                title: '型号',
                dataIndex: 'proModel',
                key: 'proModel'
            },{
                title: '全称',
                dataIndex: 'proName',
                key: 'proName'
            },{
                title: '条形码',
                dataIndex: 'barCode',
                key: 'barCode',
                sorter: (a, b) => a.barCode - b.barCode,
            },{
                title: '出库数量',
                dataIndex: 'proNum',
                key: 'proNum'
            }],
            outColumns:[
                {
                    title: '型号',
                    dataIndex: 'proModel',
                    key: 'proModel'
                },{
                    title: '简称',
                    dataIndex: 'proName',
                    key: 'proName'
                },{
                    title: '条形码',
                    dataIndex: 'barCode',
                    key: 'barCode',
                    sorter: (a, b) => a.barCode - b.barCode,
                },{
                    title: '实际数量',
                    dataIndex: 'proNum',
                    key: 'proNum',
                    render:( text, record, index)  => {
                        let isHave = true;
                        this.state.data.map((tag,key )=> {
                            if (tag.barCode === record.barCode){
                                if(tag.proNum === record.proNum){
                                    isHave = false;
                                }
                            }
                        }) 
                        if(isHave){
                            return <span style={{color:'red'}}><Tag color="red">注意</Tag>{record.proNum}</span>
                        } else {
                            return <span>{record.proNum}</span>
                        }
                    }
                },{
                    title:'操作',
                    dataIndex:'opet',
                    key:'opet',
                    render:(text, record) => (
                        <span>
                            <Popconfirm title="确认删除" onConfirm={()=>this.confirmDelete(record.proId)} onCancel={this.cancel} okText="是" cancelText="否">
                                <a>删除</a>
                            </Popconfirm>
                        </span>
                    )
                }
            ],
            p : {
                name: 'file',
                action: `${global.constants.apiPath}/upload/uploadFilePge.htm`,
                onChange:(info) => {
                  if (info.file.status !== 'uploading') {
                    //console.log(info.file, info.fileList);
                  }
                  if (info.file.status === 'done') {
                    message.success(`${info.file.name} 上传成功`);
                    this.setState({filePath : info.file.response.content.fileURL});
                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败`);
                  }
                },
            },
            page:{
                pagination:{
                    defaultPageSize:100,
                    showTotal:(total) => {return `共${total}条`;}
                }
            },
        }
    }

    //导入销售单
    importData=()=> {
        this.setState({
            loadingflag:true
        })
        axios.get(`${global.constants.apiPath}/out/importOutFile.htm`,{
            params:{
                filePath : this.state.filePath
            }
        }).then((response)=> {
            if(response.data.code === "0"){
                message.success(response.data.desc);
                this.setState({
                    data: response.data.content,
                    serialNumber:response.data.content[0].serialNumber,
                });
            } else {
                message.error(response.data.desc);
            }
            this.setState({
                loadingflag:false
            });
        })
        .catch((error) => {
            this.setState({
                loadingflag:false
            });
            console.log(error);
        });
    }

    //显示条形码输入库
    barCodeShow =() => {
        this.setState({
            barCodeShow:"show"
        });
        setTimeout(() => {
            this.input.focus();
        }, 100);
    }

    //扫描条形码
    barCodeEnd =(e) => {
        if(this.state.serialNumber == null){
            message.error("请先导入销售单");
            return;
        }
        this.setState({
            outLoadingflag:true
        })
        let barCode = e.target.value;
        axios.get(`${global.constants.apiPath}/out/scanBarCode.htm`,{
            params:{
                barCode:barCode,
                serialNumber:this.state.serialNumber
            }
        }).then((response)=>{
            if(response.data.code === "0"){
                this.input.state.value = "";
                this.setState({
                    outData:response.data.content,
                });
                this.playVid();
            } else {
                message.error(response.data.desc);
            }
            this.setState({
                outLoadingflag:false
            });
        }).catch((error) => {
            this.setState({
                outLoadingflag:false
            });
            console.log(error);
        });
    }

    //隐藏扫描录入框
    hideInput =() => {
        this.setState({
            barCodeShow:"hidden"
        });
        this.input.state.value = "";
    }

    //播放声音
    playVid=()=>{
        var myVideo=document.getElementById("audioPlay");
        myVideo.play();
    }

    //确认出库
    sureDada=()=>{
        if(this.state.outData.length === 0){
            message.error("请上传销售单并且扫描");
            return;
        }
        let isflag = true;
        for(let i in this.state.data){
            for(let j in this.state.outData){
                if(this.state.data[i].barCode === this.state.outData[j].barCode && this.state.data[i].proNum === this.state.outData[j].proNum){
                    isflag = false;
                }
            }

        }
        if(isflag){
            confirm({
                title: '实际出库与销售单不符，是否确认出库',
                onOk() {
                  this.outInventory();
                },
                onCancel() {
                  console.log('Cancel');
                },
            });
        } else {
            this.outInventory();
        }
        
    }

    outInventory = () =>{
        axios.get(`${global.constants.apiPath}/out/sureOutData.htm`,{
            params:{
                serialNumber:this.state.serialNumber
            }
        }).then((response) => {
            message.success("出库成功");
            this.setState({
                disabled:"disabled"
            })
        }).catch((error) => {
            console.log(error);
        });
    }

    //删除扫描件
    confirmDelete=(proId)=> {
        axios.get(`${global.constants.apiPath}/out/deleteDataByProId.htm`,{
            params:{
                proId:proId,
                serialNumber:this.state.serialNumber
            }
        }).then((response)=>{
            if(response.data.code === "0"){
                this.setState({
                    outData:response.data.content,
                });
            } else {
                message.error(response.data.desc);
            }
        }).catch((error)=>{
            message.error("删除失败");
            console.log(error);
        })
    }

    //导出差异商品
    expDiff=()=>{
        axios({
            method: 'post',
            url: `${global.constants.apiPath}/out/expDiff.htm`,
            transformRequest: [function (data) {
                // 对 data 进行任意转换处理
                return Qs.stringify(data)
            }],
            data: {
                outList:JSON.stringify(this.state.data),
                serialNumber:this.state.serialNumber
            }
        }).then((response)=>{
            if(response.data.code === "0"){
                window.open(response.data.content);
            } else {
                message.error("下载失败");
            }
        }).catch((error)=>{
            message.error("下载失败");
            console.log(error);
        });
    }

    cancel=(e)=> {
        
    }

    render(){
        return(
            <div>
                <Head urlpath={this.state.urlpath}></Head>
                <div>
                    <Row style={{margin:'20px'}} gutter={16}>
                        <Col span={6}>
                            <Upload {...this.state.p}>
                                <Button>
                                <Icon type="upload" />选择销售单
                                </Button>
                            </Upload>
                        </Col>
                        <Col span={6}>
                            <Button type="primary" onClick={this.importData}>导入</Button>
                        </Col>
                        <Col span={6}>
                            <Button type="primary" onClick={this.barCodeShow}>开始扫描</Button>
                        </Col>
                        <Col span={6} className={this.state.barCodeShow}>
                            <Input placeholder="商品条形码" ref={(input) => this.input = input}  onPressEnter={this.barCodeEnd} onBlur={this.hideInput}/>
                        </Col>
                    </Row>
                    <Row style={{margin:'20px'}} gutter={16}>
                        <Col span={12}>
                            <Spin tip="加载中..." spinning={this.state.loadingflag}>
                                <Table rowKey={record => record.proId} columns={this.state.columns} dataSource={this.state.data} {...this.state.page}/>
                            </Spin>
                        </Col>

                        <Col span={12}>
                            <Spin tip="加载中..." spinning={this.state.outLoadingflag}>
                                <Table rowKey={record => record.id}  columns={this.state.outColumns} dataSource={this.state.outData} {...this.state.page}/>
                            </Spin>
                        </Col>
                        <audio  id='audioPlay' >
                            <source src={mp3}></source>
                        </audio >
                    </Row>
                    <Row style={{margin:'20px'}}>
                        <Col span={16}></Col>
                        <Col span={4}>
                            <Button type="primary" onClick={this.sureDada} disabled={this.state.disabled}>确认出库</Button>
                        </Col>
                        <Col span={4}>
                            <Button type="primary" onClick={this.expDiff}>导出差异商品</Button>
                        </Col>
                    </Row>
                </div>
            </div>
        );
    }
}
export default Out;